// Modal adpater for AJAX loading modal

'use strict';

//$("form").keypress(function(e) {
//  if (e.which == 13) {
//    return false;
//  }
//});

$(document).on("change", "#cover", function() {
  $("#coverFile").val($(this).val());
})

// modal trigger
$(document).on('click open.bs.modal', '[data-toggle="modal"]', function (e) {
  
  e.preventDefault();
  var $this = $(e.currentTarget),
      url = $this.attr('href'),
      id = $this.attr('data-target').slice(1);
  
  
  if (url.indexOf('#') === 0) {
    
    $(url).modal('show');
    
  } else if(url !== 'javascript:void(0);'){
    
    var params = $this.attr('data-form-params');
    var data = params ? $('#' + params).serialize() : {};
    
    $.get(url, data, function (data) {
      $('<div class="modal fade" id="' + id + '" role="dialog" aria-hidden="true">' + data + '</div>').modal().on('hidden.bs.modal', function (e) {
        return $(e.currentTarget).remove();
      }).on('shown.bs.modal', function () {
        return $this.trigger('shown.modal');
      }).on('hidden.bs.modal', function() {
        if(id === 'upload') {
          window.location.reload();
        }
      });
    });
  }

}).off('click.bs.modal.data-api');

$(document).on('click', '.paging-jump .go-btn', function (e) {
  
  if($(this).parents("ul").hasClass("form-post-page")) {
    
    var $input = $(this).parent().find("input");
    
    if($input.val() > $input.data("total")  || $input.val() == null || $input.val().trim() == '') {
      $input.val("");
      return false;
    }
    
    var form = $("form.form-post");
    $(form).append("<input name='page' value='"+$input.val()+"' >")
    
    $(form).submit();
    
  } else {
    var $input = $(this).parent().find("input");
    
    if($input.val() > $input.data("total")  || $input.val() == null || $input.val().trim() == '') {
      $input.val("");
      return false;
    }
    
    var url = $input.data("url") + "?page=" + $input.val()
                                 + ((($input.data("querystring") === undefined || $input.data("querystring") === '')) ? '' : ("&" + $input.data("querystring")))
                                 + ($input.data("filter") === undefined ? '' : '&filter=true');
    window.location.href=url;
  }
  
})


$(document).on("click", ".form-post-page a", function (e){
  
  var page = $(this).data("page");
  var form = $("form.form-post");
  $(form).append("<input name='page' value='"+page+"' >")
  
  $(form).submit();
  
})

$(document).on("click", ".form-post-export a", function(e){
  
  var page = $(this).data("page");
  var form = $("form.form-export");
  $(form).append("<input name='page' value='"+page+"' >")
  
  var per = $(this).data("per");
  $(form).append("<input name='per_page' value='"+per+"' >")
  
  $(form).submit();
  
})


/*$(document).on('click', '.ms-table .sort', function(e) {
	
  var url = window.location.href;
  var field = $(e.currentTarget).data("field");
  var sort = "";
  
  if($(e.currentTarget).find("i").hasClass("glyphicon-triangle-bottom")) {
    sort = "ASC";
  } else if($(e.currentTarget).find("i").hasClass("glyphicon-triangle-top")) {
    sort = "DESC"
  }
  
  window.location.href = url + "&" + field + "=" + sort;
  
})*/


// tab lazy loading
$.fn.tabLazyLoading = function(url) {
  var $tab = $(this);
  $.get(url).done(function(data) {
    $($tab.data('target')).empty().append(data);
    $tab.data('loaded', 'true');
  }).fail(function() {
    if(!$($tab.data('target')).find('.loading-error').length)
    $($tab.data('target')).append('<p class="text-danger loading-error">网络异常，请稍后重新加载...</p>');
  });
}

// $(".ms-sidemenu li").each(function(e){
//   if($(this).hasClass("active")) {
//     $(this).parent().addClass("open");
//     $(this).parents("[role='presentation']").addClass("open");
//   }
// })


// ajax pagination
$.fn.ajaxPagination = function(success, fail ) {
    var that = $(this);
    $(this).on('click', ".pagination a" , function (e) {
        e.preventDefault();
        var url = $(this).data("href")
         
         $.ajax({
             url: url,
             type: 'GET',
             success: function(res) {
                 that.empty().append(res)
             }
         })
    })
    
    $(document).on('click', '.ajax-paging-jump .go-btn', function (e) {
  
      var $input = $(this).parent().find("input");
      
      if($input.val() > $input.data("total")) {
        $input.val("");
        return false;
      }
      
      var url = $input.data("url") + ((($input.data("querystring") === undefined || $input.data("querystring") === '')) ? '' : $input.data("querystring"))
                                   + ($input.data("filter") === undefined ? '' : '&filter=true')
                                   + (($input.data("querystring") === undefined || $input.data("querystring") === '') ? '?page=' : '&page=')
                                   + $input.val();
      $.ajax({
          url: url,
          type: 'GET',
          success: function(res) {
              that.empty().append(res)
          }
      })
    })
}

function initMenu() {

  var activeSubmenu = $(".umu-sidemenu").find('li.active');

  if(activeSubmenu.length > 0) {
    var parentFolder = $(activeSubmenu[0]).parents('.presentation');
    $(parentFolder).addClass('open');
    $(parentFolder).children('.subnav').addClass('open');

    $('.umu-sidemenu').animate({
        scrollTop: $(activeSubmenu[0]).offset().top
    }, 500);
  }
}

function clearAllMenu() {
  $('.umu-sidemenu').find('li').removeClass('open').removeClass('active');
  $('.umu-sidemenu').find('.subnav').removeClass('open');
}

initMenu();

$('.umu-sidemenu li a').on('click', function(event) {
    
  if($(this).parent().hasClass('presentation')) {
    
    $(this).parent().toggleClass('open');
    $(this).parent().children('.subnav').toggleClass('open');

  } else if(!$(this).parent().hasClass('presentation') && !$(this).parent().hasClass('active')){

    clearAllMenu();
    $(this).parent().addClass('active');
    initMenu();

  }

});

//click photo for close-up
$(document).on("click", ".big-close-up", function(e) {
	var currentImgPath = $(this).data("imgsrc")
  var bigImgBox = '<div class="big-img-box"><div class="img-close"></div><img src="'+ currentImgPath +'"></div>';
	$("body").append(bigImgBox)
})

$(document).on("click", ".img-close", function() {
  $(".big-img-box").remove();
})

// click btn goback
$(document).on('click', 'button.btn-go-back', function(e) {
  window.history.back();
})

// update per page
$(document).on('click', 'button.per-page-btn', function(e) {
  
  var perPage = $('input[name="perPage"]').val();
  if (perPage == null || parseInt(perPage) < 1) {
    return;
  }
  
  var currentHref = window.location.href;
  
  if (currentHref.indexOf('per_page') != -1) {
    var reg = new RegExp("per_page=(\\d+)","g"); 
    currentHref = currentHref.replace(reg, "per_page=" + perPage); 
  } else {
    if (currentHref.indexOf("?") != -1) {
      currentHref = currentHref + "&per_page=" + perPage;
    } else {
      currentHref = currentHref + "?per_page=" + perPage;
    }
  }
  
  window.location.href = currentHref;
  
});

/**
 * prevent report export
 */
$(document).on("submit", "form.ms-form", function(e){
  if(!$(this).find("button[type='submit']").attr("disabled")) {
    e.preventDefault();
    $(this).find("button[type='submit']").attr("disabled", true);
    $(this).submit();
  }
})

$(document).on('click', 'a.ms-export', function(e) {
  var that = $(this);
  if (!that.attr('disabled')) {
    that.attr("disabled", true);
    setTimeout(function() { 
      that.removeAttr('disabled');
    }, 120000);
  }
})